<!-- FAQ管理 -->
<template>
    <div class="faqManage">
        <div class="header flexbetween mb20">
            <div>
                <el-button type="primary" size="small" @click="addQuestion()" class="mr20" v-if="menuAuthCodes.includes('M125')">新增问题
                </el-button>
                <el-dropdown class="mr20" trigger="click">
                    <span class="el-dropdown-link" style="width: 200px">
                        批量操作<i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown" style="width: 200px">
                        <el-dropdown-item @click.native="batchDel">批量删除</el-dropdown-item>
                        <el-dropdown-item @click.native="batchOperate(1)">批量修改生效状态</el-dropdown-item>
                        <el-dropdown-item @click.native="batchOperate(2)">批量修改生效时间</el-dropdown-item>
                        <el-dropdown-item @click.native="batchOperate(3)">批量修改分类</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
                <el-input v-model="searchInput" placeholder="请输入内容" size="small" style="width:300px;">
                    <el-select v-model="keywordType" size="small" style="width:100px" slot="prepend">
                        <el-option label="按问题" value="question"></el-option>
                        <el-option label="按答案" value="answer"></el-option>
                    </el-select>
                    <span slot="suffix" class="iconfont icon-sousuo" @click="searchList"></span>
                </el-input>
            </div>
            <div class="iconBtn">
                <el-tooltip effect="light" content="筛选" placement="top" :enterable="false">
                    <span @click="searchVisivle = !searchVisivle" class="iconfont icon-shaixuan"></span>
                </el-tooltip>
                <el-tooltip effect="light" content="导出" placement="top" :enterable="false" class="ml20"
                            v-if="menuAuthCodes.includes('M126')">
                    <span @click="exportTable" class="iconfont icon-daochu"></span>
                </el-tooltip>
                <el-tooltip effect="light" content="导入" placement="top" :enterable="false" class="ml20"
                            v-if="menuAuthCodes.includes('M127')">
                    <span @click="importShow = !importShow" class="iconfont icon-daoru"></span>
                </el-tooltip>
            </div>
        </div>

        <div class="elementTable isFixed">
            <el-table :data="questionList" border fit :height="tableHeight" v-resize-height="tableHeight" @selection-change="changeSelect"
                      v-loading="tableLoading" tooltip-effect="light" row-key="id" ref="questionTable">
                <el-table-column type="selection" width="45"></el-table-column>
                <el-table-column label="标准问" width="250" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span class="qsIcon iconfont icon-shuzhuangtuzhankai" @click="showAnswerList(scope.row.answerList,$event)"></span>
                        <span @click="editAnswer(scope.row.id)" style="color:#6B5EE2;cursor: pointer;">
                            {{scope.row.question}}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="answerCount" label="答案数"></el-table-column>
                <el-table-column prop="similarCount" label="相似问法">
                    <template slot-scope="scope">
                        <el-link type="primary" :underline="false" @click="editSimilar(scope.row)">{{scope.row.similarCount}}</el-link>
                    </template>
                </el-table-column>
                <el-table-column label="生效状态" width="100">
                    <template slot-scope="scope">
                        <span @click="changeQueStatus(scope.row)">
                            <el-switch :value="formatAnswerStatus(scope.row.answerList)" :active-value="1" :inactive-value="0"></el-switch>
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="answerStartTime" label="生效时间" width="170" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span>{{formatAnswerTime(scope.row.answerList)}}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="updateTime" label="最后更新时间" width="170" show-overflow-tooltip></el-table-column>
                <el-table-column prop="similarCount" label="数据">
                    <template slot-scope="scope">
                        <span>{{`${scope.row.hits}/${scope.row.useFull}/${scope.row.useLess}`}}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="similarCount" label="来源">
                    <template slot-scope="scope"><span>{{formatSource(scope.row.fromSource)}}</span></template>
                </el-table-column>
                <el-table-column label="操作" width="130">
                    <template slot-scope="scope">
                        <div class="operation">
                            <el-tooltip effect="light" content="编辑答案" placement="top" :enterable="false"
                                        v-if="menuAuthCodes.includes('M122')">
                                <span class="iconfont icon-bianjidaan" @click="editAnswer(scope.row.id)"></span>
                            </el-tooltip>
                            <el-tooltip effect="light" content="编辑相似问法" placement="top" :enterable="false"
                                        v-if="menuAuthCodes.includes('M123')">
                                <span class="iconfont icon-bianjixiangsiwenfa" @click="editSimilar(scope.row)"></span>
                            </el-tooltip>
                            <el-tooltip effect="light" content="删除" placement="top" :enterable="false"
                                        v-if="menuAuthCodes.includes('M124')">
                                <span class="iconfont icon-shanchu" @click="delQuestion(scope.row.id)"></span>
                            </el-tooltip>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <div>
                <el-pagination @size-change="changePageSize" @current-change="changePageNo" :current-page="pageNo"
                               :page-sizes="[5, 10, 15, 20, 30, 50 ,100]" :page-size="pageSize" layout="->, sizes, total, prev, pager, next"
                               :total="total" background>
                </el-pagination>
            </div>
        </div>

        <div class="AnswerList">
            <el-table :data="answerList" border fit :max-height="300" tooltip-effect="light">
                <el-table-column label="答案内容" show-overflow-tooltip width="430">
                    <template slot-scope="scope">{{formatAnswer(scope.row)}}</template>
                </el-table-column>
                <el-table-column label="生效渠道" show-overflow-tooltip>
                    <template slot-scope="scope">{{scope.row.sourceNames.join(",")}}</template>
                </el-table-column>
                <el-table-column label="生效状态">
                    <template slot-scope="scope">
                        <span>{{scope.row.answerTimeLiness == 1?"开启":"关闭"}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="生效时间">
                    <template slot-scope="scope">
                        <span>{{scope.row.answerTimeType == 1 ? "永久" : scope.row.answerStartTime}}</span>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 添加编辑问题 -->
        <add-question :questionVisible.sync="questionVisible" :questionTitle.sync="questionTitle" v-on="$listeners" ref="questionDialog">
        </add-question>

        <!-- 编辑相似问法 -->
        <similar-question :similarQuestion.sync="similarQuestion" ref="similarQuestionDialog"></similar-question>

        <!-- 选择会话 -->
        <select-dialogue :selectDialogueVisible.sync="selectDialogueVisible"></select-dialogue>

        <!-- 问题导入 -->
        <import id="faqImport" :importShow.sync="importShow" :importConfig="importConfig" @importSuccess="importSuccess" />

        <!-- 问题导出 -->
        <exportExcel ref="exportExcel"></exportExcel>

        <!-- 筛选 -->
        <transition enter-active-class="animate__animated animate__fadeIn" leave-active-class="animate__animated animate__fadeOut">
            <div id="questionSearch" class="filterDialog" v-show="searchVisivle">
                <div class="searchBox">
                    <div class="searchItem">
                        <span>生效状态</span>
                        <el-select v-model="answerTimeLiness" placeholder="请选择" clearable size="small">
                            <el-option label="开启" :value="1"></el-option>
                            <el-option label="关闭" :value="0"></el-option>
                        </el-select>
                    </div>
                    <div class="searchItem">
                        <span>生效时间</span>
                        <el-date-picker v-model="answerTime" type="datetimerange" size="small" value-format="yyyy-MM-dd HH:mm:ss">
                        </el-date-picker>
                    </div>
                    <div class="searchItem">
                        <span>来源</span>
                        <el-select v-model="fromSource" placeholder="请选择" clearable size="small">
                            <el-option label="系统录入" :value="1"></el-option>
                            <el-option label="中转站" :value="2"></el-option>
                        </el-select>
                    </div>
                    <div class="searchItem">
                        <span>最后更新时间</span>
                        <el-date-picker v-model="lastUpdateTime" type="date" size="small" value-format="yyyy-MM-dd">
                        </el-date-picker>
                    </div>
                    <div class="searchItem">
                        <span>匹配规则</span>
                        <el-select v-model="matchRuleStatus" placeholder="请选择" clearable size="small">
                            <el-option label="开启" :value="1"></el-option>
                            <el-option label="关闭" :value="0"></el-option>
                        </el-select>
                    </div>
                    <div class="searchItem">
                        <span>生效渠道</span>
                        <el-select v-model="sourceId" placeholder="请选择" clearable size="small">
                            <el-option v-for="item in sourceList" :label="item.sourceName" :value="item.id" :key="item.id"></el-option>
                        </el-select>
                    </div>
                </div>
                <div class="footer">
                    <el-button size="small" type="text" @click="searchVisivle = false">取消</el-button>
                    <el-button size="small" plain @click="resetSearch">重置</el-button>
                    <el-button type="primary" size="small" @click="searchList">保存</el-button>
                </div>
            </div>
        </transition>

        <!-- 批量操作 -->
        <el-dialog :visible.sync="batchVisible" width="680px" title="批量修改" class="batchOperate" @close="batchHide">
            <el-form ref="batchForm" :model="batchForm" label-width="120px">
                <el-form-item label="生效状态" v-show="batchType == 1" prop="answerTimeLiness" required>
                    <el-switch v-model="batchForm.answerTimeLiness" :active-value="1" :inactive-value="0"></el-switch>
                </el-form-item>
                <el-form-item label="生效时间" v-show="batchType == 2" prop="answerTime" required>
                    <el-date-picker v-model="batchForm.answerTime" type="datetimerange" size="small" range-separator="至"
                                    start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="所属分类" v-show="batchType == 3" prop="classId" required>
                    <a-tree-select v-model="batchForm.classId" style="width: 450px" :tree-data="knowledgeList" allow-clear
                                   tree-node-filter-prop="title" placeholder="请选择分类" :replace-fields="replaceFields"
                                   :dropdown-style="{ maxHeight: '350px', overflow: 'auto' }" treeDefaultExpandAll />
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" type="text" @click="batchHide">取消</el-button>
                <el-button type="primary" size="small" @click="batchSubmit">保存</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { getQueList, delQuestion, exportQuestion, batchEditQuestion, editQuestionStatus } from "@/api/knowledge.js";
import elementTable from "@/components/elementTable";
import addQuestion from "./addQuestion.vue";
import similarQuestion from "./similarQuestion.vue"
import selectDialogue from "./selectDialogue.vue";
import Import from "@/components/Import";
import exportExcel from "@/components/exportExcel";
import { mapGetters } from "vuex";
export default {
    name: "faqManage",
    props: {
        classId: {
            type: String,
        },
    },
    data() {
        return {
            answerList: [],
            questionList: [],
            tableLoading: false,
            pageNo: 1,
            pageSize: 10,
            total: 0,
            keywordType: "question",
            searchInput: "",
            answerTimeLiness: "",
            answerTime: [],
            fromSource: "",
            lastUpdateTime: "",
            matchRuleStatus: "",
            sourceId: "",
            similarQuestion: false,
            questionVisible: false,
            selectDialogueVisible: false,
            questionTitle: "新增问题",
            multipleChoice: [],
            searchVisivle: false,
            importShow: false,
            importConfig: {
                css: {
                    top: "210px",
                    right: "35px",
                },
                title: "下载知识导入模板，根据模板的格式填写知识内容，填写完成后，一键导入",
                downloadUrl: "/static/download/问答答案导入模板.xlsx",
                importUrl: "/v1/admin/question/importQuestion",
            },
            batchVisible: false, //批量操作弹窗
            batchType: 1,
            batchForm: {
                answerTimeLiness: 0,
                answerTime: null,
                classId: null,
            },
            replaceFields: {
                title: "label",
                value: "id",
                children: 'children',
            },
        };
    },
    created() {
        this.getQueList();
        document.addEventListener('mouseup', (e) => {
            var faqImport = document.querySelector('#faqImport');
            var questionSearch = document.querySelector('#questionSearch');
            // if (faqImport) {
            //     if (e.target.className) {
            //         if (e.target.className.indexOf("icon-daoru") > -1 && this.importShow) return;
            //     }
            //     if (!faqImport.contains(e.target)) {
            //         this.importShow = false;
            //     }
            // }
            if (questionSearch) {
                if (e.target.className) {
                    if (e.target.className.indexOf("icon-shaixuan") > -1 && this.searchVisivle) return;
                }
                if ($(e.target).parents(".el-popper").length == 0 && !questionSearch.contains(e.target)) {
                    this.searchVisivle = false;
                }
            }
        })
    },
    mounted() {
        document.querySelector('.el-table__body-wrapper').addEventListener('scroll', () => {
            this.hideAnswerList();
        });
    },
    methods: {
        getQueList() {
            //没有查看权限
            if (!this.menuAuthCodes.includes("M121")) {
                return;
            }
            this.hideAnswerList();
            this.tableLoading = true;
            var param = {
                keywordType: this.keywordType,
                keyword: this.searchInput,
                classId: this.classId != "0" ? this.classId : "",
                lastUpdateTime: this.lastUpdateTime ? this.lastUpdateTime : "",
                sourceId: this.sourceId,
                pageNo: this.pageNo,
                pageSize: this.pageSize,
            };
            if (this.answerTime) {
                if (this.answerTime.length > 0) {
                    param.answerStartTime = this.answerTime[0];
                    param.answerEndTime = this.answerTime[1];
                }
            }
            if (this.answerTimeLiness !== "") {
                param.answerTimeLiness = this.answerTimeLiness;
            }
            if (this.matchRuleStatus !== "") {
                param.matchRuleStatus = this.matchRuleStatus;
            }
            if (this.fromSource !== "") {
                param.fromSource = this.fromSource;
            }
            getQueList(param).then((resp) => {
                this.tableLoading = false;
                if (resp.status == 0) {
                    this.total = resp.data.total;
                    this.questionList = resp.data.questionList || [];
                } else {
                    this.$antMessage.warning(resp.message);
                }
            });
        },
        changePageSize(val) {
            this.pageSize = val;
            this.getQueList();
        },
        changePageNo(val) {
            this.pageNo = val;
            this.getQueList();
        },
        changeSelect(val) {
            this.multipleChoice = val;
        },
        addQuestion() {
            this.questionVisible = true;
            this.questionTitle = "新增问题";
        },
        editSimilar(data) {
            if (!this.menuAuthCodes.includes("M123")) {
                return;
            }
            this.similarQuestion = true;
            this.$refs.similarQuestionDialog.findSimilarQuestion(data);
        },
        editAnswer(id) {
            if (!this.menuAuthCodes.includes("M122")) {
                return;
            }
            this.questionTitle = "知识点编辑";
            this.$refs.questionDialog.findQuesById(id);
            this.questionVisible = true;
        },
        delQuestion(id) {
            this.$confirm("是否确定删除?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                delQuestion({ ids: id }).then((resp) => {
                    if (resp.status == 0) {
                        this.$antMessage.success("删除成功");
                        this.pageNo = 1;
                        this.getQueList();
                    } else {
                        this.$antMessage.warning("删除失败");
                    }
                });
            }).catch();
        },
        importSuccess() {
            this.pageNo = 1;
            this.getQueList();
        },
        onExportExcelError() {
        },
        exportTable() {
            var param = {
                keywordType: this.keywordType,
                keyword: this.searchInput,
                classId: this.classId != "0" ? this.classId : "",
                lastUpdateTime: this.lastUpdateTime ? this.lastUpdateTime : "",
                sourceId: this.sourceId,
            };
            if (this.answerTime) {
                if (this.answerTime.length > 0) {
                    param.answerStartTime = this.answerTime[0];
                    param.answerEndTime = this.answerTime[1];
                }
            }
            if (this.answerTimeLiness !== "") {
                param.answerTimeLiness = this.answerTimeLiness;
            }
            if (this.matchRuleStatus !== "") {
                param.matchRuleStatus = this.matchRuleStatus;
            }
            if (this.fromSource !== "") {
                param.fromSource = this.fromSource;
            }
            this.$refs.exportExcel.showLoading();
            exportQuestion(param).then((resp) => {
                this.$refs.exportExcel.closeLoading();
                if (resp.status == 0) {
                    this.$refs.exportExcel.exports("问答列表", resp.data);
                } else {
                    this.$antMessage.warning(resp.message);
                }
            });

        },
        searchList() {
            this.searchVisivle = false;
            this.pageNo = 1;
            this.getQueList();
        },
        formatAnswerType(type) {
            var mode = "";
            switch (type) {
                case 1:
                    mode = "文本";
                    break;
                case 2:
                    mode = "富文本";
                    break;
                case 4:
                    mode = "第三方";
                    break;
                case 5:
                    mode = "转人工";
                    break;
                case 6:
                    mode = "指令";
                    break;
                case 7:
                    mode = "多轮会话";
                    break;
                case 3:
                case 8:
                case 9:
                case 10:
                case 11:
                    mode = "素材";
                    break;
            }
            return mode;
        },
        formatAnswer(row) {
            if (row.mode == 1) {
                return row.answer;
            } else if (row.mode == 7) {
                return row.dialogueName;
            }
            return ""
        },
        //批量删除
        batchDel() {
            if (this.multipleChoice.length == 0) {
                return this.$antMessage.warning("请先勾选知识点");
            }
            var ids = [];
            this.multipleChoice.forEach(item => { ids.push(item.id) });
            this.delQuestion(ids.join(","));
        },
        batchOperate(type) {
            if (this.multipleChoice.length == 0) {
                return this.$antMessage.warning("请先勾选知识点");
            }
            this.batchType = type;
            this.batchVisible = true;
        },
        batchSubmit() {
            var ids = [], param = {}, url = "";
            this.multipleChoice.forEach(item => { ids.push(item.id) });
            param.questionIds = ids.join(",")
            if (this.batchType == 1) {
                url = "/v1/admin/question/editQuestionStatus";
                param.status = this.batchForm.answerTimeLiness;
            } else if (this.batchType == 2) {
                if (this.batchForm.answerTime == null) {
                    return this.$antMessage.warning("请选择生效时间");
                }
                url = "/v1/admin/question/editQuestionAnswerTime";
                param.answerStartTime = this.batchForm.answerTime[0];
                param.answerEndTime = this.batchForm.answerTime[1];
            } else if (this.batchType == 3) {
                if (this.batchForm.classId == null) {
                    return this.$antMessage.warning("请选择分类");
                }
                url = "/v1/admin/question/editQuestionClass";
                param.classId = this.batchForm.classId;
            }
            this.batchEditQuestion(url, param);
            this.batchHide();
        },
        batchHide() {
            this.$refs.batchForm.resetFields();
            this.batchVisible = false;
        },
        batchEditQuestion(url, param) {
            batchEditQuestion(url, param).then(resp => {
                if (resp.status == 0) {
                    this.searchList();
                    this.$antMessage.success("修改成功");
                } else {
                    this.$antMessage.warning(resp.message);
                }
            });
        },
        changeQueStatus(scope) {
            var status = this.formatAnswerStatus(scope.answerList);
            var param = {
                questionIds: scope.id,
                status: status == 1 ? 0 : 1
            }
            editQuestionStatus(param).then(resp => {
                if (resp.status == 0) {
                    this.getQueList();
                    this.$antMessage.success("修改成功");
                } else {
                    this.$antMessage.warning(resp.message);
                }
            });
        },
        formatAnswerStatus(list = []) {
            var status = list.some(item => item.answerTimeLiness == 1);
            return status ? 1 : 0;
        },
        formatAnswerTime(list = []) {
            var arr = [];
            var flag = list.some(item => item.answerTimeType == 1);
            if (flag) {
                return "永久";
            }
            list.forEach(item => arr.push(item.answerStartTime));
            arr.sort((a, b) => {
                return new Date(b).getTime() - new Date(a).getTime();
            });
            return arr[0];
        },
        formatSource(source) {
            var sourceObj = {
                "1": "系统录入",
                "2": "中转站"
            }
            return sourceObj[source];
        },
        showAnswerList(answerList, event) {
            this.answerList = answerList;
            var $el = $(event.target);
            var $table = $el.parents(".el-table");
            var $tr = $el.parents(".el-table__row");
            var rect = $tr[0].getBoundingClientRect();
            $tr.siblings().find(".icon-shuzhuangtushouqi").each(function () {
                $(this).removeClass("icon-shuzhuangtushouqi").addClass("icon-shuzhuangtuzhankai");
            });
            this.$nextTick(() => {
                if ($el.hasClass("icon-shuzhuangtuzhankai")) {
                    $el.removeClass("icon-shuzhuangtuzhankai").addClass("icon-shuzhuangtushouqi");
                    $(".AnswerList").css({ "left": (rect.left + 45) + "px", "width": ($table.width() - 45) + "px" });
                    if (rect.top + $(".AnswerList").height() + 20 > document.body.clientHeight) {
                        $(".AnswerList").css("top", (rect.top - $(".AnswerList").height() - 21) + "px");
                    } else {
                        $(".AnswerList").css("top", (rect.top + rect.height) + "px");
                    }
                    $(".AnswerList").fadeIn();
                } else {
                    $el.removeClass("icon-shuzhuangtushouqi").addClass("icon-shuzhuangtuzhankai");
                    $(".AnswerList").fadeOut();
                }
            });
        },
        hideAnswerList() {
            $(".faqManage .elementTable").find(".icon-shuzhuangtushouqi").each(function () {
                $(this).removeClass("icon-shuzhuangtushouqi").addClass("icon-shuzhuangtuzhankai");
            });
            $(".AnswerList").fadeOut();
        },
        //重置搜索条件
        resetSearch() {
            this.answerTimeLiness = this.fromSource = this.lastUpdateTime = this.matchRuleStatus = this.sourceId = "";
            this.answerTime = [];
        }
    },
    computed: {
        ...mapGetters(["sourceList", "knowledgeList"]),
        tableHeight() {
            return document.body.clientHeight - 300;
        },
    },
    components: {
        elementTable,
        addQuestion,
        similarQuestion,
        selectDialogue,
        Import,
        exportExcel
    },
    watch: {
        classId(val) {
            this.classId = val;
            this.pageNo = 1;
            this.getQueList();
        },
    },
};
</script>

<style lang="scss">
.faqManage {
    #questionSearch {
        height: 290px;
    }
    .qsIcon {
        font-size: 24px;
        color: #dae1e9;
        cursor: pointer;
        position: relative;
        top: 3px;
    }
    .batchOperate {
        .el-dialog__body {
            padding-top: 30px;
        }
        .el-tree--highlight-current
            .el-tree-node.is-current
            > .el-tree-node__content {
            background: transparent;
            .el-tree-node__label {
                color: #6b5ee2;
            }
        }
        .el-tree-node__content {
            height: 34px;
        }
        .el-tree-node__expand-icon {
            font-size: 16px;
        }
    }
    .AnswerList {
        display: none;
        position: fixed;
        z-index: 10;
        padding: 10px;
        box-shadow: 0px 0px 15px 0px rgba(102, 112, 123, 0.3);
        background: #fff;
        border-radius: 6px;
    }
}
</style>
